import axios from "axios";
import { RequireURL } from "./const";
// @ts-ignore
import { ElMessage } from "element-plus";
import {useRouter} from "vue-router"
import router from "@/router/index";
import {CODE} from "../util/const"
const request = axios.create({
    baseURL: RequireURL,
    timeout: 50000,
});

request.interceptors.request.use((config) => {
    if (localStorage.getItem("token")) {
        config.headers.Authorization = localStorage.getItem("token");
    }
    return config;
});

request.interceptors.response.use(
     (res) => {
        if (res.data.code === 1) {
            if (res.headers.authorization) {
                localStorage.setItem("token", res.headers.authorization);
            }
            return res.data;
        } else {
            ElMessage.error(res.data.meg);
        }
    },
    (err) => {
        ElMessage.error(err.response.data.meg);
        if(err.response.data.code === CODE.needLogin ){
            localStorage.clear()
            // location.reload();
        }
        
        
    }
);

export default request;
